package com.motionlog.adapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.motionlog.R;
import com.motionlog.model.Database;
import com.motionlog.model.Log;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.TextView;

public class HistoryCursorAdapter extends CursorAdapter {

	private LayoutInflater mInflater;
	private Database mDb;
	private static final SimpleDateFormat sLongDateTimeFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private static final SimpleDateFormat sDateFormat = new SimpleDateFormat(
			"HH:mm");

	public HistoryCursorAdapter(Context context, Cursor c) {
		super(context, c);
		mInflater = LayoutInflater.from(context);
		mDb = Database.getInstance(context);
	}

	@Override
	public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
		return super.runQueryOnBackgroundThread(constraint);
	}

	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		View view = mInflater.inflate(R.layout.history_list_item, null);

		return view;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		android.util.Log.d("", "pos: " + cursor.getPosition());
		int pos = cursor.getPosition();
		if (pos % 2 == 0) {
			view.setBackgroundColor(Color.GREEN);
		} else {
			view.setBackgroundColor(Color.BLUE);
		}

		TextView time = (TextView) view.findViewById(R.id.time);
		TextView motion = (TextView) view.findViewById(R.id.motion);
		TextView level = (TextView) view.findViewById(R.id.level);
		TextView desc = (TextView) view.findViewById(R.id.desc);

		String ctime = cursor.getString(cursor.getColumnIndex("datetime"));
		android.util.Log.d("", "ctime: " + ctime);
		// 02-18 09:19:28.097: D/(11135): ctime: 2012-02-17 23:32:43
		try {
			Date date = sLongDateTimeFormat.parse(ctime);
			time.setText(sDateFormat.format(date));
		} catch (ParseException e) {
			time.setText("");
		}
		motion.setText(cursor.getString(cursor.getColumnIndex("motion_name")));
		level.setText(String.valueOf(cursor.getInt(cursor
				.getColumnIndex("level"))));

		long logId = cursor.getLong(cursor.getColumnIndex("_id"));
		desc.setText(mDb.getReasonSummary(logId));
	}
}
